_
platform aarch64-apple-darwin20
arch aarch64
os darwin20
system aarch64, darwin20
status
major 4
minor 4.1
year 2024
month 06
day 14
svn rev 86737
language R
version.string R version 4.4.1 (2024-06-14)
nickname Race for Your Life
2 work with file
2.1 get current directory
Code
getwd()
2.2 get all file name under current directory
Code
list.files()
[1] "1 basic R_files" "1 basic R.qmd"
[3] "1 basic R.rmarkdown" "1-basic-R.rmarkdown"
[5] "2 probability.qmd" "3 Statistics.qmd"
[7] "5 R boook.qmd" "6 data analytic in R book.qmd"
[9] "7 error handling.qmd" "hotels.csv"
[11] "images" "renv"
2.3 get all file name under currrents parent directory
# A tibble: 6 × 8
year western_champion coach result eastern_champion coach_2 finals_mvp_a
<chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 2019 Golden State Warrior… Stev… 2–4 Toronto Raptors… Nick N… Kawhi Leona…
2 2020 Los Angeles Lakers (… Fran… 4–2 Miami Heat (5) … Erik S… LeBron James
3 2021 Phoenix Suns (2) (3,… Mont… 2–4 Milwaukee Bucks… Mike B… Giannis Ant…
4 2022 Golden State Warrior… Stev… 4–2 Boston Celtics … Ime Ud… Stephen Cur…
5 2023 Denver Nuggets (1) (… Mich… 4–1 Miami Heat (8) … Erik S… Nikola Jokić
6 2024 Dallas Mavericks (5)… Jaso… 1–4 Boston Celtics … Joe Ma… Jaylen Brown
# ℹ 1 more variable:
# mw_parser_output_tooltip_dotted_border_bottom_1px_dotted_cursor_help_ref <chr>
3 handle error
using tryCatch to continues the code chunk.
Code
tryCatch({1+who},error=function(e){message(paste0('Here is some error:',e))})print('end of the code chunk')
[1] "end of the code chunk"
4 Condition with if/elif/else
Code
x <--5if(x >10){print("Non-negative number and better than 10")} elseif (x >0) {print("Non-negative number and better than 0")} else {print("Negative number")}
[1] "Negative number"
5 Loop
5.1 for Loop
Code
for (x in1:4) {print(x)}
[1] 1
[1] 2
[1] 3
[1] 4
with break statement
Code
for (x in1:6) {if (x ==4) {break}print(x)}
[1] 1
[1] 2
[1] 3
with next statement
Code
for (x in1:6) {if (x ==4) {next}print(x)}
[1] 1
[1] 2
[1] 3
[1] 5
[1] 6
5.2 using map() funcation for loop
The map functions transform their input by applying a function to each element and returning a vector the same length as the input.
loop_num=0for (i in1:6) { loop_num=loop_num+1tryCatch (print(1+i),error =function(e){message(paste("An error occurred for loop num", loop_num,":\n"), e) })}
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
5.4 while Loop
Code
i <-1while (i <6) {print(i) i <- i +1}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
with break statement
Code
i <-1while (i <6) {print(i) i <- i +1if (i ==4) {break}}
[1] 1
[1] 2
[1] 3
with next statement
Code
i =1while (i <6) { i <- i +1if (i ==4){next}print(i)}
[1] 2
[1] 3
[1] 5
[1] 6
5.5 Error handling on whie Loop: try when the error gone
Code
i=0a=0while (i <4) { a=a+1print(i)tryCatch({ asdfgaergae5gh5hae5h i=i+1 },error =function(msg){print('eeeeeeee') i=i-1print(paste0("new i : ",i)) })if(a>10){break} }
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
[1] 0
[1] "eeeeeeee"
[1] "new i : -1"
adding_ten <-function(x=10) { a=x+10return(a)}#if not define x, then x=10adding_ten()
[1] 20
6.4 check function Arguments
Code
args(adding_ten)
function (x = 10)
NULL
Many functions exhibit variadic behavior. That is, they can accept any num- ber of arguments, and it’s up to the user to decide how many arguments to provide. The functions c, data.frame, and list are all like this. When you call a function like data.frame, you can specify any number of members as arguments.
Update packages which are currently out-of-date. Currently supports CRAN, Bioconductor, other CRAN-like repositories, GitHub, GitLab, Git, and BitBucket.
11.9 make all current pakcage version back to renv list
Code
renv::restore()
11.10 update all pakcage in renv. recommand do it once a year to keep package updated.
Update packages which are currently out-of-date. Currently supports CRAN, Bioconductor, other CRAN-like repositories, GitHub, GitLab, Git, and BitBucket.
---title: "Basic R"author: "Tony Duan"execute: warning: false error: falseformat: html: toc: true toc-location: right code-fold: show code-tools: true number-sections: true code-block-bg: true code-block-border-left: "#31BAE9"---{width="300"}# R version```{r}version```# work with file## get current directory```{r}#| eval: falsegetwd()```## get all file name under current directory```{r}list.files()```## get all file name under currrents parent directory```{r}list.files("../")```## get file info```{r}#| eval: falsefile.info("6 data analytic in R book.qmd")```## create folder```{r}#| eval: falsedir.create('testing_folder')```## delete folder/file```{r}#| eval: falsefile.remove('testing_folder')```## copy file```{r}#| eval: falselibrary(fs)file_copy('test.csv', 'test2.csv')```## download file from internet```{r}#| eval: falseurl="https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-02-11/hotels.csv"download.file(url = url, destfile ="hotels.csv")```## download table from internet```{r}library(tidyverse)library(rvest)library(janitor)nba_wiki_url='https://en.wikipedia.org/wiki/List_of_NBA_champions'nba_wiki_data001=nba_wiki_url %>%read_html() %>%html_table()nba_wiki_data002=nba_wiki_data001[[2]] %>%clean_names()nba_wiki_data003=nba_wiki_data002 %>%filter(!row_number() %in%c(1, 5)) %>%mutate(year=str_sub(year, 1, 4))tail(nba_wiki_data003)```# handle errorusing tryCatch to continues the code chunk.```{r}tryCatch({1+who},error=function(e){message(paste0('Here is some error:',e))})print('end of the code chunk')```# Condition with if/elif/else```{r}x <--5if(x >10){print("Non-negative number and better than 10")} elseif (x >0) {print("Non-negative number and better than 0")} else {print("Negative number")}```# Loop## for Loop```{r}for (x in1:4) {print(x)}```with break statement```{r}for (x in1:6) {if (x ==4) {break}print(x)}```with next statement```{r}for (x in1:6) {if (x ==4) {next}print(x)}```## using map() funcation for loopThe map functions transform their input by applying a function to each element and returning a vector the same length as the input.```{r}library(tidyverse)``````{r}map(1:3, \(x) x+2 )```return number vector```{r}map_dbl(1:3, \(x) x+2 )```return char vector```{r}map_chr(1:3, \(x) x+2 )```## Error handling on for Loop:print out error```{r}stuff <-list(12, 9, 2, "cat", 25, 10, "bird")#stuff``````{r}loop_num=0for (i in1:6) { loop_num=loop_num+1tryCatch (print(1+i),error =function(e){message(paste("An error occurred for loop num", loop_num,":\n"), e) })}```## while Loop```{r}i <-1while (i <6) {print(i) i <- i +1}```with break statement```{r}i <-1while (i <6) {print(i) i <- i +1if (i ==4) {break}}```with next statement```{r}i =1while (i <6) { i <- i +1if (i ==4){next}print(i)}```## Error handling on whie Loop: try when the error gone```{r}i=0a=0while (i <4) { a=a+1print(i)tryCatch({ asdfgaergae5gh5hae5h i=i+1 },error =function(msg){print('eeeeeeee') i=i-1print(paste0("new i : ",i)) })if(a>10){break} }```# function## without Arguments```{r}my_function <-function() { print("Hello World!")}my_function()```## with Arguments```{r}adding_ten <-function(x) { a=x+10return(a)}adding_ten(5)```## with default Arguments```{r}adding_ten <-function(x=10) { a=x+10return(a)}#if not define x, then x=10adding_ten()```## check function Arguments```{r}args(adding_ten)```Many functions exhibit variadic behavior. That is, they can accept any num- ber of arguments, and it’s up to the user to decide how many arguments to provide. The functions c, data.frame, and list are all like this. When you call a function like data.frame, you can specify any number of members as arguments.```{r}args(data.frame)```## warning in functionprint out warning```{r}adding_ten <-function(x=10) { a=x+10if(a>50){warning('its better than 50') }return(a)}``````{r}adding_ten(100)```## stop in functionprint out stop error message```{r}#| eval: falseadding_ten <-function(x=10) { a=x+10if(a>50){stop('its better than 50') }return(a)}``````{r}#| eval: falseadding_ten(100)```## use try to by pass error```{r}try(adding_ten(100))5+10```# program running time```{r}start_time=Sys.time()v=matrix(1:100000000)c=v*vend_time=Sys.time()``````{r}start_time``````{r}end_time``````{r}end_time-start_time```# Package## install R package### install from Cran99% of the time will install pacakge from The Comprehensive R Archive Network(cran).<https://cran.r-project.org/>{width="300"}```{r}#| eval: falseinstall.packages('dplyr',repos ="http://cran.us.r-project.org")```### install old version from Cran```{r}#| eval: falserequire(remotes)install_version("plotly", version ="4.10.2")```### install from Github```{r}#| eval: falsepak::pkg_install("tidymodels/learntidymodels")```### install from .tar.gz```{r}#| eval: falseinstall.packages("https://cran.r-project.org/src/contrib/Archive/maptools/maptools_1.1-8.tar.gz")```### install from Bioconductor```{r}#| eval: falsepak::pkg_install("text2vec")```### install from local```{r}#| eval: falsepak::local_install("cli")```## check one package version```{r}packageVersion("tidyverse")```## check pacakge relationship```{r}pak::pkg_deps_explain("tibble", "rlang")```## check pacakge dependencies```{r}pak::pkg_deps_tree("tibble")```## check all installed package```{r}library(gt)ip =as.data.frame(installed.packages()[,c(1,3:4)])ip = ip[is.na(ip$Priority),1:2,drop=FALSE]ip |>gt() |>opt_interactive()```## check current loaded package```{r}library(dplyr)installed_pacakge =as.data.frame(installed.packages()[,c(1,3:4)])installed_pacakge = installed_pacakge[is.na(installed_pacakge$Priority),1:2,drop=FALSE]installed_pacakge |>filter(Package %in% (.packages()))|>gt() |>opt_interactive()```## list all packages on cran ```{r}cran_pacakge_num=available.packages(repos ="http://cran.us.r-project.org") |>as.data.frame()```As `r Sys.Date()` ,there are total library `r nrow(cran_pacakge_num)` on cran```{r}cran_pacakge_num|>gt() |>opt_interactive()```## check local installed old package compare with cran```{r}old.packages(repos ="http://cran.us.r-project.org")```## update all installed packageUpdate packages which are currently out-of-date. Currently supports CRAN, Bioconductor, other CRAN-like repositories, GitHub, GitLab, Git, and BitBucket.```{r}#| eval: falseupdate.packages(ask =FALSE, checkBuilt =TRUE)```## check package install loaciton```{r}.libPaths()```## uninstall pacakge```{r}#| eval: falseremove.packages('xxxxx')```# sleepThe time interval to suspend execution for, in seconds.```{r}Sys.sleep(3)```# open two R session on Mac```{r filename="Terminal"}#| eval: falseopen -n /Applications/RStudio.app```# version controlThe renv package helps you create reproducible environments for your R projects## inital renv and create renv.lock with current loaded pacakge```{r}#| eval: falserenv::init()```## show all installed pacakge```{r}library(gt)installed_pacakge =as.data.frame(installed.packages()[,c(1,3:4)])installed_pacakge = installed_pacakge[is.na(installed_pacakge$Priority),1:2,drop=FALSE]```## show all installed pacakge and loaded pacakge```{r}library(dplyr)installed_pacakge =as.data.frame(installed.packages()[,c(1,3:4)])installed_pacakge = installed_pacakge[is.na(installed_pacakge$Priority),1:2,drop=FALSE]installed_pacakge |>filter(Package %in% (.packages()))|>gt() |>opt_interactive()```## when using renv and install new pakcage```{r}# it will not work# library(lubridate)```## install new package with renv::install```{r}#| eval: falserenv::install('lubridate')``````{r}library(lubridate)```## check current package and renv package```{r}#| eval: falserenv::status()```## update lock file```{r}#| eval: falserenv::snapshot()```## check status again```{r}#| eval: falserenv::status()```## make all current pakcage version back to renv list```{r}#| eval: falserenv::restore()```## update all pakcage in renv. recommand do it once a year to keep package updated.Update packages which are currently out-of-date. Currently supports CRAN, Bioconductor, other CRAN-like repositories, GitHub, GitLab, Git, and BitBucket.```{r}#| eval: falserenv::update()```## update renv itself only```{r}#| eval: falserenv::upgrade()```## close renv in a project```{r}#| eval: falserenv::deactivate()```## re enable renv in a project```{r}#| eval: falserenv::activate()```# reccord code run time```{r}start_time=Sys.time()for (kk in1:5) {print(kk)Sys.sleep(1) }end_time=Sys.time()time_used=end_time-start_timetime_used```# stop when code run too longstop the count down at 1.5 sec```{r}#| warning: true#| error: truelibrary(R.utils)foo <-function() {print("Tic")for (kk in1:100) {print(kk)Sys.sleep(0.1) }print("Tac")}withTimeout({foo()}, timeout =1.5, onTimeout ="warning")```# check website connectionwhen connect_result= 2 it means connection is ok```{r}url='www.bing.com'connect_result=system(paste0('ping -c 1 ',url))connect_result```when connect_result= 68 it means connection is fail```{r}url='www.bingxxxxx.com'connect_result=system(paste0('ping -c 1 ',url))connect_result```# Using Python## select python versioncheck whether python is available```{r}reticulate::py_available()```check python version```{r}reticulate::py_config()```## select python versionSet up Python:Using python 3.11 instead of 3.13. It need to restart first```{r}#| eval: falseSys.setenv(RETICULATE_PYTHON ="/Library/Frameworks/Python.framework/Versions/3.11/bin/python3.11")library(reticulate)use_python("/Library/Frameworks/Python.framework/Versions/3.11/bin/python3.11")``````{python}#| eval: falsefrom platform import python_versionprint(python_version())```## run python in R```{r}#| eval: falsesource_python("flights.py")``````{r, attr.output='.details summary="sessionInfo()"'}sessionInfo()```